package data;

import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedList;

import system.Config;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;

public class ChallengeRecord {

	public LinkedList<RecordItem> list = new LinkedList<RecordItem>();;
	
	public ChallengeRecord(BasicDBList dblist) {
		BasicDBObject item;
		if (dblist != null) {
			for (Object obj:dblist) {
				item = (BasicDBObject)obj;
				list.add(new RecordItem(item));
			}
		}
	}
	
	public synchronized void add(String enemyGuid, boolean win, int isChallenger) {
		RecordItem record;
		record = findEnemy(enemyGuid);
		if (record != null) {
			list.remove(record);
		} else if (list.size() == Config.CHALLENGE_RECORD_CAPACITY) {
			record = list.pollFirst();
		} else {
			record = new RecordItem(new BasicDBObject());
		}
//		record.setName(enemy.name);
		record.setGUID(enemyGuid);
//		record.setLevel(enemy.level);
//		record.setSex(enemy.sex);
		record.setWin(win);
		record.setChallenger(isChallenger);
		record.setDate(Calendar.getInstance().getTime());
		list.add(record);
	}

	public RecordItem findEnemy(String guid) {
		Iterator<RecordItem> ite = list.iterator();
		RecordItem item;
		while (ite.hasNext()) {
			item = ite.next();
			if (item.getGUID().equals(guid))
				return item;
		}
		return null;
	}

//	public synchronized void serialize(ChannelBuffer buf) {
//		if (list == null) {
//			buf.writeInt(0);
//		} else {
//			buf.writeInt(list.size());
//			Iterator<RecordItem> ite = list.descendingIterator();
//			RecordItem item;
//			while (ite.hasNext()) {
//				item = ite.next();
//				item.serialize(buf);
//			}
//		}
//	}
	
	public void writeDB(BasicDBList dblist) {
		for (RecordItem item: list) {
			dblist.add(item.db);
		}
		
	}
}
